package cn.com.gas.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.com.common.constants.Constants;
import cn.com.common.result.DataResult;
import cn.com.gas.entity.GasOilpriceEntity;
import cn.com.gas.service.GasOilpriceService;
import cn.com.gas.vo.excel.GasOilpriceExcel;
import cn.com.system.service.impl.HttpSessionService;
import cn.com.util.TsBqUtils;

/**
 * 油价维护
 *
 * @author shaochangyang
 * @email l2l84o7o5@live.com
 * @date 2024-03-13 23:33:29
 */
@RestController
@RequestMapping("/gas/maintain")
public class GasMaintainController {
	@Autowired
	private GasOilpriceService gasOilpriceService;
	@Autowired
	private HttpSessionService httpSessionService;
	@Value("${file.path}")
	private String filePath;
	@Value("${file.url}")
	private String fileUrl;

	@ApiOperation(value = "新增")
	@PostMapping("/add")
	// @RequiresPermissions("gasOilprice:add")
	@ResponseBody
	public DataResult add(@RequestBody GasOilpriceEntity gasOilprice) {

		gasOilprice.setDeleted(Constants.DELETEED_NOT);
		gasOilprice.setCreateId(httpSessionService.getCurrentUserId());
		gasOilprice.setCreateTime(new Date());

		gasOilpriceService.save(gasOilprice);
		return DataResult.success();
	}

	@ApiOperation(value = "删除")
	@DeleteMapping("/delete")
	// @RequiresPermissions("gasOilprice:delete")
	@ResponseBody
	public DataResult delete(@RequestBody @ApiParam(value = "id集合") List<String> ids) {
		gasOilpriceService.removeByIds(ids);
		return DataResult.success();
	}

	@ApiOperation(value = "更新")
	@PutMapping("/update")
	// @RequiresPermissions("gasOilprice:update")
	@ResponseBody
	public DataResult update(@RequestBody GasOilpriceEntity gasOilprice) {

		gasOilprice.setUpdateId(httpSessionService.getCurrentUserId());
		gasOilprice.setUpdateTime(new Date());

		gasOilpriceService.updateById(gasOilprice);
		return DataResult.success();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@ApiOperation(value = "查询分页数据")
	@PostMapping("/list")
	// @RequiresPermissions("gasOilprice:list")
	@ResponseBody
	public DataResult findListByPage(@RequestBody GasOilpriceEntity gasOilprice) throws ParseException {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		Page page = new Page(gasOilprice.getPage(), gasOilprice.getLimit());
		LambdaQueryWrapper<GasOilpriceEntity> queryWrapper = Wrappers.lambdaQuery();
		// 查询条件示例
		if (!StringUtils.isEmpty(gasOilprice.getCreateTimeStart())) {
			queryWrapper.ge(GasOilpriceEntity::getCreateTime, sdf.parse(gasOilprice.getCreateTimeStart() + " 00:00:00"));
		}
		if (!StringUtils.isEmpty(gasOilprice.getCreateTimeEnd())) {
			queryWrapper.le(GasOilpriceEntity::getCreateTime, sdf.parse(gasOilprice.getCreateTimeEnd() + " 23:59:59"));
		}

		IPage<GasOilpriceEntity> iPage = gasOilpriceService.page(page, queryWrapper);
		return DataResult.success(iPage);
	}

	@PostMapping("/exportData")
	@ResponseBody
	public DataResult exportData(@RequestBody GasOilpriceEntity gasOilprice)
			throws java.io.IOException, ParseException {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		LambdaQueryWrapper<GasOilpriceEntity> queryWrapper = Wrappers.lambdaQuery();
		// 查询条件示例

		if (!StringUtils.isEmpty(gasOilprice.getCreateTimeStart())) {
			queryWrapper.ge(GasOilpriceEntity::getCreateTime, sdf.parse(gasOilprice.getCreateTimeStart() + " 00:00:00"));
		}
		if (!StringUtils.isEmpty(gasOilprice.getCreateTimeEnd())) {
			queryWrapper.le(GasOilpriceEntity::getCreateTime, sdf.parse(gasOilprice.getCreateTimeEnd() + " 23:59:59"));
		}

		queryWrapper.orderByDesc(GasOilpriceEntity::getCreateTime);

		List<GasOilpriceEntity> list = gasOilpriceService.list(queryWrapper);

		if (list.size() > 0) {

			List<GasOilpriceExcel> gasOilpriceExcelList = new ArrayList<>();

			for (GasOilpriceEntity entity : list) {

				GasOilpriceExcel gasOilpriceExcel = GasOilpriceExcel.builder().id(entity.getId())
						.gasoline(entity.getGasoline()).diesel(entity.getDiesel()).zero(entity.getZero())
						.ninetyTwo(entity.getNinetyTwo()).ninetyFive(entity.getNinetyFive())
						.ninetyEight(entity.getNinetyEight()).createTime(entity.getCreateTime()).build();

				gasOilpriceExcelList.add(gasOilpriceExcel);

			}

			String fileName = TsBqUtils.getUUID() + ".xlsx";

			String excelPath = filePath + fileName;
			OutputStream out = null;

			try {
				out = new FileOutputStream(excelPath);
				ExcelWriter writer = EasyExcelFactory.getWriter(out);

				Sheet sheet1 = new Sheet(1, 0, GasOilpriceExcel.class);
				sheet1.setSheetName("数据");
				writer.write(gasOilpriceExcelList, sheet1);
				// 将上下文中的最终 outputStream 写入到指定文件中
				writer.finish();
				File excelFile = new File(excelPath);
				List<Object> excelFileInfo = new ArrayList<>();
				excelFileInfo.add(fileName);
				excelFileInfo.add(excelFile.length());
				excelFileInfo.add(fileUrl + "/" + fileName);

				return DataResult.success(excelFileInfo);

			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return DataResult.fail("xlsx生成失败：" + e.toString());
			} finally {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					return DataResult.fail("xlsx生成失败：" + e.toString());
				}

			}

		} else {
			return DataResult.fail("传入的ids为null！");
		}
	}

}
